<template>
  <div class="ar-map-layer">
    <div ref="mapCon" id="mapCon"></div>
  </div>
</template>

<script setup>
import "ol/ol.css";
import { ref, onMounted, defineComponent } from "vue";
import { Map, View } from "ol";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { fromLonLat, toLonLat } from "ol/proj";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import GeoJSON from "ol/format/GeoJSON";
import Feature from "ol/Feature";
import { LineString, Point, Polygon } from "ol/geom";
import { Icon, Style, Stroke, Circle, Fill, Text } from "ol/style";
import Overlay from "ol/Overlay.js";
import { Image as ImageLayer } from "ol/layer.js";
import ImageWMS from "ol/source/ImageWMS.js";
import VectorTileSource from "ol/source/VectorTile";
import VectorTileLayer from "ol/layer/VectorTile";
import MVT from "ol/format/MVT";
import { defaults } from "ol/interaction/defaults";
import PointerInteraction from "ol/interaction/Pointer";
import { getbyuserid } from "@/api/event.js";
const emit = defineEmits(["changeGd"]);
const props = defineProps({
  currentHigh: Object,
  high: Boolean,
  eventInfo: Object,
});
console.log("props.eventInfo", props.eventInfo);
const mapCon = ref(null);
const animating = ref(false);
let map;
let arrPoint = ref([]);
let polyonArr = ref([]);

// 添加点位
let highLayer = null;
let lowLayer = null;
let allhighFectures = [];
let alllowFectures = [];
let currentHigh = ref({ cameraId: "" });
let gdList = ref([]);

// 修改选中状态
const changeHighBg = (data) => {
  currentHigh.value = data;
  for (let i = 0; i < allhighFectures.length; i++) {
    let attrs = allhighFectures[i].get("attrs");
    allhighFectures[i].setStyle(
      new Style({
        image: new Icon({
          src: "/images/new/lowicon.png",
          width: 32,
          height: 35,
        }),
        text: new Text({
          text: attrs.deviceCount, // 从要素属性中获取文本
          font: "12px Arial", // 字体样式
          fill: new Fill({ color: "#fff" }), // 文本填充颜色
          offsetX: 0, // ���平偏移
          offsetY: 1, // ��直偏移
          textAlign: "center", // 文本对齐方式
          textBaseline: "center", // 文本基线
        }),
      })
    );
  }

  let emitvalue = JSON.parse(JSON.stringify(data));
  console.log("emitvalue", emitvalue);
  emit("changeGd", emitvalue);
};

const addHighlight = () => {
  debugger;
  // 创建矢量图层
  const vectorSource = new VectorSource();
  const vectorLayer = new VectorLayer({
    source: vectorSource,
  });
  map.addLayer(vectorLayer);
  // 定义扇形的中心点、半径、起始角度和结束角度
  const center = fromLonLat([117.74256851451989, 39.00380206757584]); // 中心点坐标
  const radius = 5000; // 半径（单位：米）
  const startAngle = (30 * Math.PI) / 180; // 起始角度（30度）
  const endAngle = (120 * Math.PI) / 180; // 结束角度（120度）
  // 生成扇形的点集
  const points = [toLonLat(center)]; // 第一个点是中心点
  for (let angle = startAngle; angle <= endAngle; angle += Math.PI / 180) {
    const x = center[0] + radius * Math.cos(angle);
    const y = center[1] + radius * Math.sin(angle);
    points.push(toLonLat([x, y]));
  }
  points.push(toLonLat(center)); // 最后一个点回到中心点
  // 创建扇形几何图形
  const sector = new Polygon([points]);

  // 创建渐变填充样式
  const gradientFill = (feature, resolution) => {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
    canvas.width = 500;
    canvas.height = 500;
    // 创建径向渐变
    const gradient = context.createRadialGradient(
      toLonLat(center)[0],
      toLonLat(center)[1],
      0, // 渐变起始点（中心）
      toLonLat(center)[0],
      toLonLat(center)[1],
      radius // 渐变结束点（半径）
    );
    gradient.addColorStop(0, "rgba(255, 0, 0, 1)"); // 中心颜色（红色）
    gradient.addColorStop(1, "rgba(255, 255, 0, 0.5)"); // 边缘颜色（黄色，半透明）

    return new Style({
      fill: new Fill({
        color: gradient,
      }),
      stroke: new Stroke({
        color: "#000000", // 边框颜色
        width: 2, // 边框宽度
      }),
    });
  };

  // 创建扇形要素
  const sectorFeature = new Feature({
    geometry: sector,
  });

  // 将渐变样式应用到扇形要素
  sectorFeature.setStyle(gradientFill);

  // 将扇形要素添加到矢量图层
  vectorSource.addFeature(sectorFeature);
};

const getView = () => {
  localStorage.setItem("polython", JSON.stringify(polyonArr.value));
  return;
  let view = map.getView();
  let center = view.getCenter();
  console.log(center);
  center[0] = center[0] - 1;
  center[1] = center[1] - 1;
  view.setCenter(center);
  map.render();

  view.animate({
    // center: fromLonLat([114.28, 34.54]),
    center: [114.28, 34.54],
    zoom: 7,
    duration: 1000,
  });

  // 获取图层方法:等等
  // map.getLayers().item[1].getSource().on('click')
};

// 获取事件高点设备
const getData = async () => {
  try {
    let params = {
      busizEventIdLong: props.eventInfo.busizEventId,
    };
    let { data } = await getbyuserid(params);
    console.log("data", data);

    if (data.eventLocation) {
      gdList.value = [
        {
          lng: data.eventLocation.longitude,
          lat: data.eventLocation.latitude,
        },
      ];
      if (map) {
        map.getView().animate({
          center: [data.eventLocation.longitude, data.eventLocation.latitude],
          zoom: 13,
          duration: 500,
        });
      }
    }
    console.log("gdList高点设备", gdList.value);
    addhightLayer();
  } catch (e) {
    console.error(e);
  }
};
let allPoint = ref([]);
// 获取人员设备
const getData1 = async () => {
  try {
    let params = {
      busizEventIdLong: props.eventInfo.busizEventId,
    };
    let { data } = await getbyuserid(params);
    allPoint.value = data.userLocations;
    addlowLayer();
  } catch (e) {
    console.error(e);
  }
};

// 添加高点设备
const addhightLayer = async () => {
  if (!map) return;
  let arr = gdList.value;
  console.log("addPointLayer", arr);
  // 1、初始化点位的图层
  highLayer = new VectorLayer({
    source: new VectorSource(),
  });
  allhighFectures = [];
  for (let i = 0; i < arr.length; i++) {
    if (!arr[i].lng || !arr[i].lat) return;
    // 2、创建点位的feature
    let feature = new Feature({
      geometry: new Point([arr[i].lng, arr[i].lat]),
      attrs: {
        ...arr[i],
        high: true,
      },
      draggable: false,
    });

    feature.setStyle(
      new Style({
        image: new Icon({
          src: "/images/higt.svg",
          width: 40,
          height: 40,
        }),
        text: new Text({
          text: "", // 从要素属性中获取文本
          font: "12px Arial", // 字体样式
          fill: new Fill({ color: "#fff" }), // 文本填充颜色
          offsetX: 0, // 水平偏移
          offsetY: 1, // 垂直偏移
          textAlign: "center", // 文本对齐方式
          textBaseline: "center", // 文本基线
        }),
      })
    );
    allhighFectures.push(feature);
  }

  // 3 、 将feature添加到layer中
  highLayer.getSource().addFeatures(allhighFectures);
  // 4、将feauture添加到layser
  map.addLayer(highLayer);
  highLayer.setZIndex(9);
};

// 添加低点设备
const addlowLayer = () => {
  if (!map) return;
  if (lowLayer) {
    map.getLayers().remove(lowLayer);
    lowLayer = null;
  }
  let arr = allPoint.value || [];
  // 1、初始化点位的图层
  if (!lowLayer) {
    lowLayer = new VectorLayer({
      source: new VectorSource(),
    });
  }
  alllowFectures = [];

  for (let i = 0; i < arr.length; i++) {
    if (!arr[i].longitude || !arr[i].latitude) return;
    // 2、创建点位的feature
    let feature = new Feature({
      geometry: new Point([arr[i].longitude, arr[i].latitude]),
      attrs: {
        ...arr[i],
      },
      draggable: false,
    });
    feature.setStyle(
      new Style({
        image: new Icon({
          src: "/images/peopleLow.svg",
          width: 32,
          height: 35,
        }),
        text: new Text({
          text: "", // 从要素属性中获取文本
          font: "12px Arial", // 字体样式
          fill: new Fill({ color: "#fff" }), // 文本填充颜色
          offsetX: 0, // 水平偏移
          offsetY: 1, // 垂直偏移
          textAlign: "center", // 文本对齐方式
          textBaseline: "center", // 文本基线
        }),
      })
    );
    alllowFectures.push(feature);
  }
  // 3 、 将feature添加到layer中
  lowLayer.getSource().addFeatures(alllowFectures);

  // 4、将feauture添加到layser

  map.addLayer(lowLayer);
  lowLayer.setZIndex(9);
};

watch(
  () => props.currentHigh,
  (newval, oldval) => {},
  {
    deep: true,
    immediate: true,
  }
);

watch(
  () => props.high,
  (newval, oldval) => {},
  {
    deep: true,
    immediate: true,
  }
);
onMounted(async () => {
  map = new Map({
    layers: [
      new ImageLayer({
        source: new ImageWMS({
          url: "/geoserver/bcd/wms",
          params: { LAYERS: "bcd", VERSION: "1.1.0" },
          ratio: 1,
          serverType: "geoserver",
        }),
      }),
    ],
    target: mapCon.value,
    view: new View({
      center: [117.74256851451989, 39.00380206757584],
      projection: "EPSG:4326",
      minZoom: 4,
      zoom: 13,
    }),
    interactions: defaults({
      doubleClickZoom: true,
    }),
  });

  // 地图注册点击事件
  map.on("click", (event) => {
    let point = event.coordinate;
    // 获取点击的要素
    const clickedFeature = map.forEachFeatureAtPixel(event.pixel, (feature) => {
      return feature;
    });
    let data = clickedFeature.get("attrs");
    if (data.id) {
      changeHighBg(data);
    }
  });

  map.on("postrender", () => {});
  // eventSourceDesc==人工上报,eventSource==100
  // 人工上报 不会在地图上打点
  let isManualReport = props.eventInfo.eventSource;
  console.log("isManualReport是不是人工上报", isManualReport);
  if (isManualReport !== "100") {
    await getData();
    await getData1();
  }

  // // 确保地图完全初始化后再定位
  if (gdList.value.length > 0) {
    const [eventPoint] = gdList.value;
    map.getView().animate({
      center: [eventPoint.lng, eventPoint.lat],
      zoom: 13,
      duration: 500,
    });
  }
});
</script>

<style lang="scss" scoped>
.ar-map-layer {
  width: 100%;
  height: 100%;
  #mapCon {
    width: 100%;
    height: 100%;
  }
}
</style>
